package com.example.asus.happy;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.asus.happy.service.address.Address;
import com.example.asus.happy.service.application.MyApplication;
import com.example.asus.happy.service.finaldata.FinalData;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;

import static android.widget.Toast.makeText;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener{
    private String url;//请求地址
    private Intent intent;
    private TextView registerTV,backTV;//注册,返回
    //帐号，密码框
    private EditText userNameET,pwdET;
    //登录按钮
    private Button loginBtn;
    private ProgressDialog dialog;//加载框
    //安全检测
    private TextView textView6;
    private Context mContext;


    //初始化控件
    public  void init(){
        registerTV = (TextView)findViewById(R.id.registerTV);
        userNameET = (EditText) findViewById(R.id.userNameET);
        pwdET = (EditText) findViewById(R.id.pwdET);
        loginBtn = (Button) findViewById(R.id.loginBtn);
        backTV = (TextView) findViewById(R.id.backTV);
        textView6=(TextView)findViewById(R.id.textView6);

        //userNameET.setText(getApp().getUserName());
    }


    //Handler
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {

            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    //获取后台数据
                    String response = (String)msg.obj;
                    //Toast.makeText(LoginActivity.this, response, Toast.LENGTH_SHORT).show();
                    //response==1,登录成功
                    if (response.equals("1")){
                        //自定义Toast
                        makeText(LoginActivity.this, FinalData.LOGIN_SUCC, Toast.LENGTH_SHORT).show();
                        //将userName存到application
                        getApp().setUserName(userNameET.getText().toString());
                        //new MainActivity().init();
                        finish();
                    }else {
                        makeText(LoginActivity.this, FinalData.LOGIN_FAIL, Toast.LENGTH_SHORT).show();
                    }
                    dialog.dismiss();//关闭加载框
                    break;
                default:
                    makeText(LoginActivity.this, FinalData.NONETWORK, Toast.LENGTH_SHORT).show();
                    break;
            }
        }

    };

    //HttpPostRequest建立连接（）
    private void HttpPostRequest(final String url){
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                List<NameValuePair> carteList = new ArrayList<NameValuePair>();
                try{
                    httpPost.setEntity(new UrlEncodedFormEntity(carteList,"UTF-8"));
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    if (httpResponse.getStatusLine().getStatusCode() == 200){//状态码200
                        HttpEntity httpEntity = httpResponse.getEntity();
                        String count = EntityUtils.toString(httpEntity,"UTF-8");
                        Message message = new Message();
                        message.what = 0;
                        message.obj = count.toString();
                        handler.sendMessage(message);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //初始化方法
        init();
        //注册按钮点击事件
        registerTV.setOnClickListener(this);
        //登录点击事件
        loginBtn.setOnClickListener(this);
        //返回
        backTV.setOnClickListener(this);

    }

    //重写的按钮点击事件
    @Override
    public void onClick(View view) {

       switch (view.getId()){
           case R.id.registerTV :
               intent = new Intent(LoginActivity.this,RegisterActivity.class);
               startActivity(intent);
               break;
           case R.id.loginBtn :
               //执行登录操作
               //获取用户名和密码
               String userName = userNameET.getText().toString();
               String pwd = pwdET.getText().toString();
               dialog = ProgressDialog.show(LoginActivity.this, "", FinalData.LOGINING, true, true);
               url = Address.ADDRESS+"findLoginJsp?u_userName="+userName+"&u_passWord="+pwd;
               HttpPostRequest(url);
               break;
           case R.id.backTV :
               finish();
               break;
           case R.id.textView6: // 还未成功完善
               textView6.setOnClickListener(new View.OnClickListener() {
                   @Override
                   public void onClick(View v) {
                       midToast("提莫队长，正在送命~该功能未开发！",Toast.LENGTH_SHORT);
                   }
               });
               break;
       }

    }
    // 自定义toast信息
    private void midToast(String str, int showTime) {
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.view_toast_custom,(ViewGroup) findViewById(R.id.lly_toast));
        ImageView img_logo = (ImageView) view.findViewById(R.id.img_logo);
        TextView tv_msg = (TextView) view.findViewById(R.id.tv_msg);
        tv_msg.setText(str);
        Toast toast = new Toast(mContext);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(view);
        toast.show();
    }

    //获取application
    public MyApplication getApp(){
        return (MyApplication) getApplicationContext();
    }
}
